<script setup>
import { ref, reactive, watch } from "vue";
import { onShow, onReachBottom } from "@dcloudio/uni-app";
import { request } from "../../../common/http";
import { ApiUrl } from "../../../common/ApiUrl";
import {
	getCurrentDate,
	getCurrentAndPreviousDayUTC,
	millisToDateString,
	millisToUTCString,
	formatUTCDateToCustomFormat,
} from "@/utils/date";
import { orderNoFilter, Toast } from "@/utils";
import * as XLSX from "xlsx";
import { storeToRefs } from "pinia";
import { useOrderStore } from "@/store/order";
import { useUserStore } from "@/store/user";
const orderStore = useOrderStore();
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

let orderCondition = ref({
	/* 支付单号 */
	orderNo: "",
	/* 机器编号 */
	machineNo: "",
	/* 页码 */
	pageNum: 1,
	/* 每页显示的记录数量 */
	pageSize: 10,
	/* 订单类型过滤 1：普通订单 */
	orderMoreType: 1,
	/* 订单状态 -1：全部 1：支付成功 2：退款中 3：退款失败 4：退款成功 */
	payStatus: -1,
	/* 起始时间 */
	startDate: "",
	/* 结束时间 */
	endDate: "",
})
/* 当天日期-天 */
let currentDay = ref(null);
let statOrder = ref({});
let pageCount = ref(0);
let orderList = ref([]);
/* 起始时间文本 */
let startDateText = ref("");
/* 结束时间文本 */
let endDateText = ref("");
/* 是否显示订单状态弹窗 */
let showOrderStatus = ref(false);
/* 是否显示开始日期弹窗 */
let showStartDate = ref(false);
/* 是否显示结束日期弹窗 */
let showEndDate = ref(false);
/* 是否显示退款弹窗 */
let showRefund = ref(false);
/* 验证操作密码弹窗 */
let verifyPassword = ref(false);
let password = ref();
/* 当前选中的要退款的订单 */
let refundOrder = ref({
	/* 订单编号 */
	orderNo: null,
	/* 退款金额 */
	refundAmount: null,
	/* 商户ID */
	merchantId: null,
	/* 退款原因 */
	reason: null,
});
/* 订单状态弹窗列表数据 */
let payStatusList = reactive([
	[
		{ text: "全部", value: -1 },
		{ text: "待支付", value: 0 },
		{ text: "支付成功", value: 1 },
		{ text: "退款中", value: 2 },
		{ text: "退款失败", value: 3 },
		{ text: "退款成功", value: 4 },
		{ text: "取消订单", value: 5 },
	]
]);
let payStatusName = ref("全部");
let orderThead = ref(["", "支付单号", "消费金额", "订单状态", "出货状态", "机器编号", "操作" ]);
const payStatus = ref({
	0: "待支付",
	1: "支付成功",
	2: "退款中",
	3: "退款失败",
	4: "退款成功",
	5: "取消订单"
})
const orderStatus = ref({
	0: "出货失败",
	1: "出货成功",
	2: "等待取货",
	3: "线下取货",
	4: "取货超时",
	10: "押金未退"
})

onShow(() => {
	startDateText.value = getCurrentDate();
	endDateText.value = getCurrentDate();
	orderCondition.value.startDate = getCurrentAndPreviousDayUTC().previousUTCDate;
	orderCondition.value.endDate = getCurrentAndPreviousDayUTC().currentUTCDate;
	currentDay.value = String(new Date().getDate()).padStart(2, '0');
	getStarOrder();
	/* 获取订单列表数据 */
	getOrderList();
})

const getStarOrder = () => {
	request({
		url: `${ApiUrl.OrderUrl}/statOrder`,
		method: "post",
		data: {
			...orderCondition.value
		}
	}).then(res => {
		if (res.status == 0) {
			statOrder.value = res.data;
		} else {
			Toast(res.msg || "网络异常", "error");
		}
	})
}

/* 详情按钮点击事件 */
const handleToOrderDetial = (item) => {
	orderStore.setCurrentOrder(item);
	uni.navigateTo({
		url: `/pages/index/OrderHistory/Detail?id=${item.id}`
	})
}

/* 列表页退款按钮点击事件 */
const handleRefund = (item) => {
	showRefund.value = true;
	refundOrder.value = item;
	refundOrder.value.orderNo = item.orderNo;
	refundOrder.value.refundAmount = item.totalAmount;
	refundOrder.value.merchantId = item.merchantId;
}

/* 退款弹窗确定按钮点击事件 */
const handleRefundConfirm = () => {
	if (!refundOrder.value.reason) {
		return Toast("请输入退款原因");
	}
	/* 关闭退款弹窗 */
	showRefund.value = false;
	/* 打开验证操作密码弹窗 */
	setTimeout(() => {
		verifyPassword.value = true;
	}, 500)
}

/* 上一页/下一页按钮点击事件 */
const handlePageChange = (operation) => {
	if (operation == 'prev') {
		/* 上一页 */
		if (orderCondition.value.pageNum == 1) {
			return Toast("已经是首页了!");
		} else {
			orderCondition.value.pageNum--;
		}
	} else {
		/* 下一页 */
		if (pageCount.value <= orderCondition.value.pageNum) {
			return Toast("已经是尾页了!");
		}
		orderCondition.value.pageNum++;
	}
	/* 获取订单列表数据 */
	getOrderList();
}

/* 订单状态弹窗确定按钮点击事件 */
const handleOrderStatusConfirm = (e) => {
	const item = e.value[0];
	payStatusName.value = item.text;
	orderCondition.value.payStatus = item.value;
	showOrderStatus.value = false;
	/* 获取订单列表数据 */
	getOrderList();
}

/* 开始时间弹窗确定按钮点击事件 */
const handleStartDateConfirm = (e) => {
	startDateText.value = millisToDateString(e.value);
	orderCondition.value.startDate = millisToUTCString(e.value);
	/* 关闭开始时间弹窗 */
	showStartDate.value = false;
	/* 获取订单列表数据 */
	getOrderList();
}

/* 结束时间弹窗确定按钮点击事件 */
const handleEndDateConfirm = (e) => {
	endDateText.value = millisToDateString(e.value);
	orderCondition.value.endDate = millisToUTCString(e.value);
	/* 关闭结束时间弹窗 */
	showEndDate.value = false;
	/* 获取订单列表数据 */
	getOrderList();
}

/* 验证密码弹窗确定按钮点击事件 */
const handleVerifyPasswordConfirm = () => {
	if (!password.value) {
		return Toast("请输入密码!");
	}
	password.value = encodeURIComponent(password.value);
	request({
		url: `${ApiUrl.UserUrl}/judgePwd?pwd=${password.value}`,
		method: "post",
		data: {}
	}).then(res => {
		if (res.status == 0) {
			/* 校验订单是否存在 */
			request({
				url: `${ApiUrl.verifyOrderNo}/${refundOrder.value.orderNo}`
			}).then(res => {
				/* 判断是否有返回数据 */
				if (res.data) {
					/* 如果有返回数据，则调用新订单退款接口 */
					request({
						url: `${ApiUrl.newOrderRefund}`,
						method: "post",
						data: {
							orderNo: refundOrder.value.orderNo
						}
					}).then(data => {
						if (data.status == 0) {
							Toast(data.msg, "success");
							password.value = "";
							refundOrder.value.reason = "";
							verifyPassword.value = false;
							/* 获取订单列表数据 */
							getOrderList();
						} else {
							Toast(data.msg, "error");
						}
					})
					
				} else {
					/* 没有返回数据或者返回为空，则调用旧订单退款接口 */
					request({
						url: `${ApiUrl.OrderUrl}/refund`,
						method: "post",
						data: {
							...refundOrder.value
						}
					}).then(data => {
						if (data.status == 0) {
							Toast(data.msg, "success");
							password.value = "";
							refundOrder.value.reason = "";
							verifyPassword.value = false;
							/* 获取订单列表数据 */
							getOrderList();
						} else {
							Toast(data.msg, "error");
						}
					})
				}
			})
			
		} else {
			Toast(res.msg, "error");
		}
	})
}

/* 查询按钮点击事件 */
const handleSearch = () => {
	orderList.value = [];
	/* 获取订单列表数据 */
	getOrderList();
}

const getDay = (item) => {
	return item.createTime.substring(8, 10);
}

/* 导出按钮点击事件 */
const handleExport = () => {
	// // 新建工作簿
	// let workbook = XLSX.utils.book_new()
	// // 处理数据
	// let data = orderList.value.map(item => {
	// 	return {
	// 		商户号: item.merchantOrderNo,
	// 		商户名称: item.merchantName,
	// 		机器号: item.machineNo,
	// 		支付单号: item.orderNo,
	// 		商品: item.goodsName,
	// 		成本价: item.costPrice,
	// 		交易金额: item.totalAmount,
	// 		购买数量: item.goodsNum,
	// 		交易状态: `${payStatus.value[item.payStatus]}`,
	// 		通道: `${item.channelType == 1 ? "微信" : item.channelType == 2 ? "支付宝" : ""}`,
	// 		交易时间: formatUTCDateToCustomFormat(item.createTime),
	// 	}
	// })
	request({
		url: `${ApiUrl.OrderUrl}/download`,
		method: "post",
		data: {
			...orderCondition.value
		}
	}).then(res => {
		
	})
}

/* 退押金按钮点击事件 */
const handleRefundDeposit = () => {
	const temp = orderList.value.filter(item => item.isChecked);
	if (temp.length < 1) return Toast("请先选择要退押金的订单");
	if (temp.length > 0) {
		const refundList = temp.filter(item => item.isRefund == 0);
		if (refundList.length < 1) return Toast("选择的订单中没有可以退押金的订单");
		refundList.map(item => {
			request({
				url: `${ApiUrl.getRefundDeposit}`,
				method: "post",
				data: {
					orderNo: item.orderNo,
					refundPrice: item.price,
				}
			}).then(res => {
				/* 获取订单列表数据 */
				getOrderList();
			})
		})
	}
}

/* 获取订单列表数据 */
const getOrderList = () => {
	request({
		url: `${ApiUrl.OrderUrl}/list?pageNum=${orderCondition.value.pageNum}&pageSize=${orderCondition.value.pageSize}`,
		method: "post",
		data: {
			...orderCondition.value
		}
	}).then(res => {
		if (res.status == 0) {
			res.data.list.map(item => {
				item.isChecked = false;
				/* 查询订单押金支付状态 */
				request({
					url: `${ApiUrl.getOrderDepositStatus}/${item.orderNo}`
				}).then(res => {
					if (res.data) {
						const { price, isRefund } = res.data;
						// if (isRefund == 0) item.orderStatus = 10;
						item.price = price;
						item.isRefund = isRefund;
					}
				})
			});
			orderList.value = res.data.list;
			pageCount.value = res.data.pages;
		} else {
			Toast(res.msg, "error");
		}
	})
}

/* 监听支付单号 */
watch(() => orderCondition.value.orderNo, (val) => {
	if (!val) {
		/* 获取订单列表数据 */
		getOrderList();
	}
})

/* 监听机器编号 */
watch(() => orderCondition.value.machineNo, (val) => {
	if (!val) {
		/* 获取订单列表数据 */
		getOrderList();
	}
})
</script>

<template>
	<view class="order_history">
		<view class="query_box">
			<view class="form_item">
				<view class="label">支付单号</view>
				<input v-model="orderCondition.orderNo" type="number" placeholder-class="placeholder" placeholder="请输入支付单号" />
			</view>
			<view class="form_item">
				<view class="label">机器编号</view>
				<input v-model="orderCondition.machineNo" type="number" maxlength="6" placeholder-class="placeholder" placeholder="例如:100001" />
			</view>
			<view class="form_item">
				<view class="label">订单状态</view>
				<view class="select" @click="showOrderStatus = true">
					{{ payStatusName }}
					<image src="/static/image/icon/icon_arrow_right.png" mode="aspectFill"></image>
				</view>
			</view>
			<view class="form_item" @click="showStartDate = true">
				<view class="label">起始时间</view>
				<text>{{ startDateText }}</text>
				<image src="/static/image/icon/icon_arrow_right.png" mode="aspectFill"></image>
			</view>
			<view class="form_item" @click="showEndDate = true">
				<view class="label">结束时间</view>
				<text>{{ endDateText }}</text>
				<image src="/static/image/icon/icon_arrow_right.png" mode="aspectFill"></image>
			</view>
			<view class="order_info">
				<view>订单数量：{{ statOrder?.successCount }}</view>
				<view>营业额：{{ statOrder?.successMoney }}元</view>
				<view>利润：{{ statOrder?.totalProfit }}元</view>
			</view>
			<view class="btns">
				<view @click="handleExport">导出</view>
				<view class="btn_query" @click="handleSearch">查询</view>
				<view class="btn_query" @click="handleRefundDeposit">退押金</view>
			</view>
		</view>
		
		<view class="order_list">
			<view class="order_thead">
				<view class="order_thead_item" :class="[`thead${index + 1}`]" v-for="(item, index) in orderThead" :key="index">{{ item }}</view>
			</view>
			<block v-if="orderList.length > 0">
				<view class="order_item" v-for="(item, index) in orderList" :key="item.id">
					<view class="check" @click="item.isChecked = !item.isChecked">
						<image v-if="item.isChecked" src="/static/image/icon_check.png" mode="aspectFill"></image>
						<image v-else src="/static/image/icon_no_check.png" mode="aspectFill"></image>
					</view>
					<text class="order_no">{{ orderNoFilter(item.payChannelOrderNo) }}</text>
					<text class="amount">{{ item.totalAmount }}</text>
					<text class="pay_status">{{ payStatus[item.payStatus] }}</text>
					<view class="order_status" :class="{ 'refund': item.isRefund == 0}">{{ orderStatus[item.orderStatus] }}</view>
					<text class="marchine_no">{{ item.machineNo }}</text>
					<view class="operation">
						<text @click="handleToOrderDetial(item)">详情</text>
						<text v-if="item.payStatus == 1 && getDay(item) == currentDay" @click="handleRefund(item)">退款</text>
					</view>
				</view>
			</block>
			<view v-else class="no_data">暂无数据</view>
		</view>
		<view v-if="orderList.length > 0" class="page_button">
			<view @click="handlePageChange('prev')">上一页</view>
			<view @click="handlePageChange('next')">下一页</view>
		</view>
		<!-- 订单状态弹窗 -->
		<u-picker
			:show="showOrderStatus"
			:columns="payStatusList"
			@cancel="showOrderStatus = false"
			@confirm="handleOrderStatusConfirm" />
		<!-- 开始时间弹窗 -->
		<u-datetime-picker
			:show="showStartDate"
			v-model="startDateText"
			mode="date"
			@cancel="showStartDate = false"
			@confirm="handleStartDateConfirm" />
		<!-- 结束时间弹窗 -->
		<u-datetime-picker
			:show="showEndDate"
			v-model="endDateText"
			mode="date"
			@cancel="showEndDate = false"
			@confirm="handleEndDateConfirm" />
		<!-- 退款弹窗 -->
		<u-popup :show="showRefund" mode="center" :round="16">
			<view class="popup refund_popup">
				<view class="title">退款</view>
				<view class="refund_row">订单号：{{ refundOrder.orderNo }}</view>
				<view class="refund_row">交易金额：{{ refundOrder.refundAmount }}</view>
				<view class="refund_row">退款金额：{{ refundOrder.refundAmount }}</view>
				<view class="refund_row reason">
					退款原因：
					<input v-model.trim="refundOrder.reason" type="text" placeholder="退款原因" placeholder-class="reason_placeholder" maxlength="16" />
				</view>
				<view class="footer">
					<view @click="showRefund = false">取消</view>
					<view @click="handleRefundConfirm">确定</view>
				</view>
			</view>
		</u-popup>
		<!-- 验证操作密码弹窗 -->
		<u-popup :show="verifyPassword" mode="center" :round="16">
			<view class="popup update_password_popup">
				<view class="title">密码</view>
				<input v-model.trim="password" type="password" placeholder="请输入密码" placeholder-class="password_placeholder" />
				<view class="footer">
					<view @click="verifyPassword = false">取消</view>
					<view @click="handleVerifyPasswordConfirm">确定</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<style lang='scss'>
.order_history {
	background: #F8F9FB;
	width: 100%;
	min-height: 100vh;
	box-sizing: border-box;
	padding-bottom: 140rpx;
	.query_box {
		box-sizing: border-box;
		padding: 0 32rpx;
		width: 100%;
		background: #ffffff;
		margin-bottom: 24rpx;
		.form_item {
			width: 100%;
			display: flex;
			align-items: center;
			box-sizing: border-box;
			padding: 28rpx 0;
			box-shadow: inset 0rpx -1rpx 0rpx 0rpx #EBEEF1;
			.label {
				font-weight: 500;
				font-size: 28rpx;
				color: #3B3D3D;
				line-height: 33rpx;
				margin-right: 28rpx;
			}
			input {
				font-size: 28rpx;
				color: #B6BDBD;
				line-height: 33rpx;
				background: none;
				border: none;
				border-radius: none;
				outline: none;
			}
			.placeholder {
				color: #B6BDBD;
			}
			text {
				display: inline-block;
				flex: 1;
				text-align: right;
				font-size: 28rpx;
				color: #B6BDBD;
				line-height: 33rpx;
			}
			image {
				flex-shrink: 0;
				width: 32rpx;
				height: 32rpx;
				margin-left: 12rpx;
			}
			.select {
				display: flex;
				flex: 1;
				align-items: center;
				justify-content: flex-end;
				color: #B6BDBD;
				font-size: 28rpx;
			}
		}
		.order_info {
			width: 100%;
			padding: 24rpx 0 0;
			box-sizing: border-box;
			display: flex;
			align-items: center;
			justify-content: space-between;
			view {
				font-size: 24rpx;
				color: #FF6619;
				line-height: 32rpx;
			}
		}
		.btns {
			width: 100%;
			height: 112rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			box-sizing: border-box;
			padding: 0 30rpx;
			view {
				width: 152rpx;
				height: 64rpx;
				border-radius: 32rpx;
				border: 2rpx solid #FF776A;
				font-size: 28rpx;
				color: #FF4638;
				line-height: 33rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				&.btn_query {
					background: linear-gradient( 129deg, #FF776A 0%, #FF4638 100%);
					border: none;
					color: #ffffff;
				}
			}
		}
	}
	.order_list {
		.order_thead {
			width: 750rpx;
			height: 64rpx;
			background: #FF766C;
			display: flex;
			box-sizing: border-box;
			padding: 18rpx 0;
			.order_thead_item {
				font-weight: 500;
				font-size: 20rpx;
				color: #ffffff;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: center;
				&:not(:last-child) {
					border-right: 4rpx solid #FFE5E5;
				}
				&.thead1 {
					width: 50rpx;
				}
				&.thead2 {
					width: 120rpx;
				}
				&.thead3,
				&.thead4,
				&.thead5,
				&.thead6,{
					width: 110rpx;
				}
				&:last-child {
					flex: 1;
				}
			}
		}
		.order_item {
			width: 750rpx;
			height: 64rpx;
			background: #FFFFFF;
			font-size: 20rpx;
			color: #3B3D3D;
			box-sizing: border-box;
			display: flex;
			&:nth-child(odd) {
				background: #FFF3F2;
			}
			.check {
				width: 50rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				image {
					width: 30rpx;
					height: 30rpx;
				}
			}
			text {
				display: flex;
				align-items: center;
				justify-content: center;
				&.order_no {
					width: 120rpx;
				}
				&.amount,
				&.pay_status,
				&.marchine_no {
					width: 110rpx;
				}
			}
			.order_status {
				width: 110rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				&.refund {
					color: #FF4638;
				}
			}
			.operation {
				display: flex;
				flex: 1;
				align-items: center;
				justify-content: center;
				box-sizing: border-box;
				padding: 0 20rpx;
				font-weight: bold;
				color: #25DFA5;
				text {
					&:nth-child(2) {
						color: #FF4638;
						margin-left: 20rpx;
					}
				}
			}
		}
		.no_data {
			width: 750rpx;
			height: 64rpx;
			background: #FFFFFF;
			font-size: 20rpx;
			color: #3B3D3D;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
	.page_button {
		margin: 40rpx 73rpx 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		view {
			width: 282rpx;
			height: 60rpx;
			border-radius: 40rpx;
			border: 2rpx solid #FF776A;
			box-sizing: border-box;
			font-size: 28rpx;
			color: #FF4638;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}
	.refund_popup,
	.update_password_popup {
		width: 560rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		box-sizing: border-box;
		padding: 40rpx 0 0;
		.refund_row {
			font-size: 24rpx;
			line-height: 28rpx;
			color: #999999;
			padding: 0 0 0 60rpx;
			margin-bottom: 16rpx;
			&.reason {
				margin-bottom: 28rpx;
				display: flex;
				align-items: center;
				input {
					flex: 1;
				}
			}
			.reason_placeholder {
				color: #999999;
				font-size: 24rpx;
			}
		}
		
	}
	.update_password_popup {
		input {
			height: 64rpx;
			margin: 0 60rpx 28rpx;
			font-size: 24rpx;
			line-height: 28rpx;
			color: #999999;
			border: 2rpx solid rgba(#999999, 0.5);
			box-sizing: border-box;
			padding: 0 20rpx;
			text-align: center;
		}
	}
	.popup {
		.title {
			font-weight: 500;
			font-size: 32rpx;
			line-height: 38rpx;
			color: #353535;
			letter-spacing: 1px;
			text-align: center;
			margin-bottom: 22rpx;
		}
		.footer {
			width: 100%;
			height: 112rpx;
			border-top: 2rpx solid rgba(0, 0, 0, 0.1);
			display: flex;
			align-items: center;
			view {
				height: 100%;
				flex: 1;
				font-weight: 500;
				font-size: 32rpx;
				box-sizing: border-box;
				display: flex;
				align-items: center;
				justify-content: center;
				&:last-child {
					color: #FF4638;
					border-left: 2rpx solid rgba(0, 0, 0, 0.1);
				}
			}
		}
	}
}
</style>